package com.baosight.sczx.common.zm.basetools.listener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.spring.SpringApplicationContext;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.dao.Dao;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cn.domain.ZMCNStock;


public class StockDayCarryForward {
	private static Dao dao = (Dao)SpringApplicationContext.getBean("dao");

	public String stockDayCarryForward(){
		String date=StaticTools.getDate();
		Map<String,String> _map=new HashMap<String,String>();
		_map.put("fdCurrentDate", date);
		ZMCNStock s=new ZMCNStock();
		List<?> _list=dao.query("ZMCNStock.stockforautorun", _map);
		if(_list.size()>0){
			//当天记录已经生成，直接退出
			return "ok";
		}
		_list=dao.query("ZMCNStock.stockforautorun", new HashMap<String,String>());
		if(_list.size()>0){
			//数据库中有库存记录存在，将最大日期那天库存记录复制到当前日期
			s=(ZMCNStock)_list.get(0);
			String maxDate=s.getFdCurrentDate();
			for(int i=0;i<_list.size();i++){
				s=(ZMCNStock)_list.get(i);
				if(s.getFdCurrentDate().equals(maxDate)){
					//只复制最大日期一天的库存记录
					s.setFdKeyId(TablePk.getInstance().getNextValue("t_cn_stock"));
					s.setFdCurrentDate(date);
					dao.insert("ZMCNStock.insert",s);
				}else{
					//最大日期那天记录复制完成后退出
					break;
				}	
			}
		}else{
			//数据库中为空，初始化库存记录
			//根据煤质中心下属各分站，每个站一条库存记录
			String mzzxCode = InitialData.getInstance().getEiBlockByNo("cmes.cn.meizhiCode").getCellStr(0, "display");
			
			if(mzzxCode == null || mzzxCode.trim().equals("")) {
				mzzxCode = "D.10223";
			}
			_map.put("parentName", mzzxCode);
			_map.put("mzzxCode", mzzxCode);
			_list = dao.query("ZM02.queryInterface", _map);
            for(int i=0;i<_list.size();i++){
            	String oraName=(String)((Map<?, ?>)_list.get(i)).get("orgName");
            	if(oraName.indexOf("站")>=0){
					s.setFdKeyId(TablePk.getInstance().getNextValue("t_cn_stock"));
					s.setFdCurrentDate(date);
					s.setFdDepartmentId((String)((Map<?, ?>)_list.get(i)).get("orgCode"));
					s.setFdDepartment(oraName);
					s.setFdYear(StaticTools.getYearStr(date));
					s.setFdMonth(StaticTools.getMonthStr(date));
					dao.insert("ZMCNStock.insert",s);
            	}
            }
		}
		return "ok";
	}
}
